import java.util.*;

class Solution {
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        Stack<Integer> stack = new Stack<>();
        Map<Integer, Integer> map = new HashMap<>();
        for(int i = 0; i < nums2.length; i++) {
            while(!stack.empty() && stack.peek() < nums2[i]) {
                map.put(stack.peek(), nums2[i]);
                stack.pop();
            }
            stack.push(nums2[i]);  
        }
        while(!stack.empty()) {
            map.put(stack.peek(), -1);
            stack.pop();
        }
        int[] r = new int[nums1.length];
        for(int i = 0; i < nums1.length; i++) {
            r[i] = map.get(nums1[i]);
        }
        return r;
    }
}